package com.ruoyi.washer.common;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxWechatTools {

    private static final Logger logger = LoggerFactory.getLogger(WxWechatTools.class);

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.appsecret}")
    private String secret;

    @Value("${wx.mch_id}")
    private String mchId;

    @Value("${wx.key_v2}")
    private String key_v2;

    @Value("${wx.key_v3}")
    private String key_v3;

    @Value("${wx.notify_url}")
    private String notify_url;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private QRCodeUtil qrCodeUtil;
    /*
    获取openid
     */
    public String getOpenid(String jscode)throws Exception{
        // 根据小程序穿过来的code想这个url发送请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + jscode + "&grant_type=authorization_code";
        System.out.println("url======="+url);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        String str=restTemplate.getForObject(url,String.class,paramMap);
        // 转成Json对象 获取openid
        JSONObject jsonObject = JSONObject.parseObject(str);
        System.out.println("url==="+url);
        System.out.println("str==="+str);
        //我们需要的openid，在一个小程序中，openid是唯一的
        String openid = jsonObject.get("openid").toString();
        return openid;
    }

    /*
获取getAccessToken
 */
    public String getAccessToken(){

        String url="https://api.weixin.qq.com/cgi-bin/token?appid="+appid+"&secret="+secret+"&grant_type=client_credential";
        Map<String, Object> paramMap = new HashMap<String, Object>();
        String str=restTemplate.getForObject(url,String.class,paramMap);
        JSONObject jsonObject = JSONObject.parseObject(str);
        String accessToken=jsonObject.getString("access_token");
        return accessToken;
    }

    /*
    获取订单号
     */

    public String getPrepayId(String out_trade_no,String description,int total,String openId){
        String prepayId=null;
        String url="https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("appid",appid);
        jsonObject.put("mchid",mchId);
        jsonObject.put("description",description);
        jsonObject.put("out_trade_no",out_trade_no);
        jsonObject.put("notify_url",notify_url);
        JSONObject jsonObject2=new JSONObject();
        jsonObject2.put("total",total);
        jsonObject2.put("currency","CNY");
        jsonObject.put("amount",jsonObject2);
        JSONObject jsonObject3=new JSONObject();
        jsonObject3.put("openid",openId);
        jsonObject.put("payer",jsonObject3);
        System.out.println(jsonObject.toString());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //用HttpEntity封装整个请求报文
        HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), headers);
        //        开始调用
        //        参数1：目标请求地址
        //        参数2：请求体
        //        参数3：目标请求接口的返回值类型（execute接口的返回值类型）
        JSONObject result = restTemplate.postForObject(url, request, JSONObject.class);
        prepayId=result.getString("prepay_id");
        return prepayId;
    }
    /*
    虚拟商品发货处理
     */
    @Async
    public void uploadShipping(String transactionId,String goodstype,String openId){
        try{
            Thread.sleep(20000);
        }catch (Exception e){
            e.printStackTrace();
        }
        String accessToken=getAccessToken();
        String url="https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token="+accessToken;
        JSONObject jsonObject=new JSONObject();
        JSONObject jsonObject1=new JSONObject();
        jsonObject1.put("order_number_type",2);
        jsonObject1.put("transaction_id",transactionId);
        jsonObject1.put("mchid",mchId);
        jsonObject.put("order_key",jsonObject1);
        jsonObject.put("logistics_type",3);
        jsonObject.put("delivery_mode",1);
        JSONObject jsonObject2=new JSONObject();
        if(goodstype!=null&&goodstype.equals("3")){
            jsonObject2.put("item_desc","答疑卡虚拟商品");
        }else if(goodstype!=null&&goodstype.equals("4")){
            jsonObject2.put("item_desc","电子书虚拟商品");
        }
        JSONArray jsonArray=new JSONArray();
        jsonArray.add(jsonObject2);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String formatDate = simpleDateFormat.format(new Date(System.currentTimeMillis()));


        jsonObject.put("shipping_list",jsonArray);
        jsonObject.put("upload_time",formatDate);

        JSONObject jsonObject3=new JSONObject();
        jsonObject3.put("openid",openId);
        jsonObject.put("payer",jsonObject3);
        logger.info("url======="+url);
        logger.info(jsonObject.toString());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //用HttpEntity封装整个请求报文
        HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), headers);
        //        开始调用
        //        参数1：目标请求地址
        //        参数2：请求体
        //        参数3：目标请求接口的返回值类型（execute接口的返回值类型）
        JSONObject result = restTemplate.postForObject(url, request, JSONObject.class);
        logger.info("result======="+result);
        String errmsg=result.getString("errmsg");
        if(errmsg!=null&&errmsg.equals("ok")) {

        }
    }

    /*
    获取小程序的scheme码
     */
    public void getQRCode(HttpServletResponse response,String deviceSn, String env_version)throws Exception{
        String filePath = RuoYiConfig.getProfile()+"/"+deviceSn+"_"+env_version+"_sn.png";
        File f = new File(filePath);
        byte[] res=null;
        if(f.exists()){
            res= Files.readAllBytes(Paths.get(filePath));
        }else{
            String accessToken=getAccessToken();
            String url="https://api.weixin.qq.com/wxa/getwxacode?access_token="+accessToken;
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("path","/pages/index/index?deviceSn="+deviceSn);
            jsonObject.put("env_version",env_version);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            //用HttpEntity封装整个请求报文
            HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), headers);
            //        开始调用
            //        参数1：目标请求地址
            //        参数2：请求体
            //        参数3：目标请求接口的返回值类型（execute接口的返回值类型）
            res = restTemplate.postForObject(url, request,byte[].class);
            saveQRCodeFile(res,deviceSn,env_version);
            res= Files.readAllBytes(Paths.get(filePath));
        }
        if(response!=null){
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment; filename="+deviceSn+"_"+env_version+".zip");
            response.addHeader("Content-Length", "" + res.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(res, response.getOutputStream());
        }
    }

    public String saveQRCodeFile(byte[] res,String deviceSn, String env_version)throws Exception{
        String path = RuoYiConfig.getProfile()+"/"+deviceSn+"_"+env_version+".jpg";
        File f = new File(path);
        BufferedOutputStream out=null;
        try {
            if(res.length<=500) {//如果byte字节流小于500，说明返回的是err错误码而非buffer
                return new String(res);
            }else {
                out = new BufferedOutputStream(
                        new FileOutputStream(f));
                out.write(res);
                out.flush();
                out.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
            return "IO Error";
        }finally {
            if(out!=null){
                out.close();
                out=null;
            }
        }
        File f0 = new File(path);
        BufferedImage image=ImageIO.read(f0);
        String newpath = RuoYiConfig.getProfile()+"/"+deviceSn+"_"+env_version+"_sn.png";
        QRCodeUtil.getQRCode(image,deviceSn,deviceSn,newpath);
        return null;
    }


    /*
 获取小程序的获取scheme码
  */
    public JSONObject getUrlScheme(){
        String accessToken=getAccessToken();
        String url="https://api.weixin.qq.com/wxa/generatescheme?access_token="+accessToken;
        JSONObject jsonObject=new JSONObject();
        JSONObject jsonObject1=new JSONObject();
        jsonObject1.put("path","pages/me/expressage/expressage");
        jsonObject.put("jump_wxa",jsonObject1);
        logger.info("result1======="+jsonObject.toString());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //用HttpEntity封装整个请求报文
        HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), headers);
        //        开始调用
        //        参数1：目标请求地址
        //        参数2：请求体
        //        参数3：目标请求接口的返回值类型（execute接口的返回值类型）
        JSONObject res = restTemplate.postForObject(url, request,JSONObject.class);

        logger.info("result2======="+res);

        return res;
    }

    public static void main(String args[]){
        System.out.println(new WxWechatTools().getPrepayId("111111","2222222",10,"111000000000"));
        //System.out.println(UUID.fastUUID().toString().replaceAll("-",""));
    }
}
